package com.task.sql.schedule.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.task.sql.schedule.common.ApiResult;
import com.task.sql.schedule.common.PageResult;
import com.task.sql.schedule.constant.ResultCode;
import com.task.sql.schedule.domain.entity.SqlContent;
import com.task.sql.schedule.mapper.SqlContentMapper;
import com.task.sql.schedule.service.SqlContentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.task.sql.schedule.domain.qo.SqlContentQO;
import com.task.sql.schedule.domain.vo.SqlContentVO;
import com.task.sql.schedule.domain.dto.SqlContentDTO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;


/**
 1.  服务实现类
 2.  3. @author donghai.liu
 4. @time 2024-09-10
 */
@Service
public class SqlContentServiceImpl extends ServiceImpl<SqlContentMapper, SqlContent> implements SqlContentService {

@Resource
private SqlContentMapper mapper;

@Override
public PageResult<SqlContentVO> page(SqlContentQO qo) {
    List<SqlContentVO> data = mapper.listSqlContent(qo);
    int total = mapper.countSqlContent(qo);
    PageResult<SqlContentVO> pageResult = PageResult.success(data, total);
    pageResult.setPageSize(qo.getPageSize());
    pageResult.setPageNum(qo.getPageNum());
    int pages = total % qo.getPageSize() == 0 ? total / qo.getPageSize() : total / qo.getPageSize() + 1;
    pageResult.setPages(pages);
    return pageResult;
}

@Override
@Transactional
public ApiResult<Long> save(SqlContentDTO dto) {
    SqlContent entity = new SqlContent();
    BeanUtil.copyProperties(dto, entity);
    mapper.insert(entity);
    return ApiResult.success(entity.getId());
}

@Override
@Transactional
public ApiResult<Long> update(SqlContentDTO dto) {
    if(null == dto.getId()) {
        return ApiResult.error(ResultCode.PARAM_ERROR);
    }
    SqlContent entity = new SqlContent();
    BeanUtil.copyProperties(dto, entity);
    mapper.updateById(entity);
    return ApiResult.success(entity.getId());
}
}
